import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Table, Input, Button, message } from "antd";
import { useForm } from "antd/es/form/Form";
import { ColumnsType } from "antd/es/table";
import "./index.less";

import { MembersModal } from "./MembersModal";
import { AddMemberModal } from "./AddMemberModal";
import { CreateGroupModal } from "./CreateGroupModal";

import { getGroupList } from "@/api/group";

interface SearchGroup {
    name: string;
}
interface GroupSearchResult {
    id: number;
    name: string;
    createTime: Date;
    type: boolean;
    userCount: number;
    userIds: Array<number>;
}

export function Group() {
    const navigate = useNavigate();
    const [form] = useForm();
    const [groupResult, setGroupResult] = useState<Array<GroupSearchResult>>([]);
    const [isMemberModalOpen, setIsMemberModalOpen] = useState<boolean>(false);
    const [chatroomId, setChatroomId] = useState<number>(-1);
    const [isAddMemberModalOpen, setIsAddMemberModalOpen] = useState<boolean>(false);
    const [isCreateGroupModal, setIsCreateGroupModal] = useState<boolean>(false);
    const [queryKey, setQueryKey] = useState<string>('');

    // 泛型传入GroupSearchResult，是为了得到dataIndex的类型提示
    const columns: ColumnsType<GroupSearchResult> = [
        {
            title: '名称',
            dataIndex: 'name'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            render: (_, record) => {
                return new Date(record.createTime).toLocaleString();
            },
        },
        {
            title: '人数',
            dataIndex: 'userCount'
        },
        {
            title: '操作',
            render: (_, record) => (
                <div>
                    <a href="#" onClick={(e) => {
                        e.preventDefault();
                        navigate('/chat', {
                            state: {
                                chatroomId: record.id
                            }
                        })
                    }}>聊天</a>&nbsp;
                    <a href="#" onClick={() => {
                        setChatroomId(record.id);
                        setIsMemberModalOpen(true);
                    }}>详情</a>&nbsp;
                    <a href="#" onClick={() => {
                        setChatroomId(record.id);
                        setIsAddMemberModalOpen(true);
                    }}>添加成员</a>
                </div>
            )
        }
    ];

    const searchGroupList = async (values: SearchGroup) => {
        try {
            const resp: any = await getGroupList(values.name);
            setGroupResult(resp.filter((item: GroupSearchResult) => item.type).map((item: GroupSearchResult) => {
                return {
                    ...item,
                    key: item.id
                }
            }))
        } catch (error: any) {
            message.error(error?.data?.message || '系统繁忙，请稍后再试');
        }
    }


    useEffect(() => {
        searchGroupList({ name: form.getFieldValue('name') });
    }, [])

    return <div className="group">
        <div className="group_form">
            <Form
                layout="inline"
                colon={false}
                onFinish={searchGroupList}
            >
                <Form.Item label='名称' name='name'><Input /></Form.Item>
                <Form.Item label=' '><Button type="primary" htmlType="submit">搜索</Button></Form.Item>
                <Form.Item label=' '><Button type="primary" style={{ backgroundColor: 'green' }} onClick={()=>{ setIsCreateGroupModal(true); }}>创建群聊</Button></Form.Item>
            </Form>
        </div>
        <div className="group_table">
            <Table columns={columns} dataSource={groupResult}></Table>
        </div>
        <MembersModal chatroomId={chatroomId} isOpen={isMemberModalOpen} handleClose={() => { setIsMemberModalOpen(false) }} queryKey={queryKey} />
        <AddMemberModal chatroomId={chatroomId} isOpen={isAddMemberModalOpen} handleClose={() => {
            setIsAddMemberModalOpen(false);
            searchGroupList({ name: form.getFieldValue('name') });
            setQueryKey(Math.random().toString().slice(2, 10));
        }} />
        <CreateGroupModal isOpen={isCreateGroupModal} handleClose={() => { setIsCreateGroupModal(false); searchGroupList({ name: form.getFieldValue('name') }) }} />
    </div>
}